package com.chuck.blogpro.aop;

import com.chuck.blogpro.mapper.LogMapper;
import com.chuck.blogpro.pojo.Log;
import com.chuck.blogpro.utils.JWTUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@Aspect
public class TimerAspect {

    @Autowired
    LogMapper logMapper;

    @Autowired
    HttpServletRequest request;

    // 切入点表达式: 当前 controller 目录下的所有方法
    @Pointcut("execution(* com.chuck.blogpro.controller.*.*(..))")
    public void controllerPointCut() {

    }

    // 将方法执行时间记录到日志中
    @Around("controllerPointCut()") // 切入点
    public Object recordTime(ProceedingJoinPoint joinPoint) throws Throwable {
        long begin = System.currentTimeMillis();

        Object result = joinPoint.proceed();

        long end = System.currentTimeMillis();

        String content = joinPoint.getSignature() + "执行时间：" + (end - begin);
        Log log = new Log();
        log.setContent(content);

        // 从 Jwt 里获取用户信息
        String token = request.getHeader("token");
        Map<String, Object> map = JWTUtils.checkToken(token);
        if (map != null) {
            log.setUserId((Integer) map.get("id"));

        }
        // 操作的controller
        log.setName(String.valueOf(joinPoint.getClass()));

        // System.out.println(log);

        logMapper.add(log);

        return result;
    }

//    @Before("execution(* com.chuck.blogpro.controller.*.*(..))")
//    public void before() {
//        System.out.println("before");
//    }
//
//    @After("execution(* com.chuck.blogpro.controller.*.*(..))")
//    public void after() {
//        System.out.println("after");
//    }
//
//    @AfterReturning(pointcut = "execution(* com.chuck.blogpro.controller.*.*(..))")
//    public void afterReturning() {
//        System.out.println("afterReturning");
//    }
//
//    @AfterThrowing(pointcut = "execution(* com.chuck.blogpro.controller.*.*(..))")
//    public void afterThrowing() {
//        System.out.println("afterThrowing");
//    }
}
